package com.gitee.ice1938.module.admin.filemanager.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;

import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.gitee.ice1938.module.admin.filemanager.fun.FileNode;

public abstract class DownloadUtils {
	public static void download(FileNode fileNode, HttpServletRequest request, HttpServletResponse response) {
		response.reset();
		String fileName = fileNode.getFileName();
		String downloadFileName = null;
		try {
			String agent = request.getHeader("user-agent");
			if (fileName != null && !fileName.trim().isEmpty()) {
				if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
					downloadFileName = "=?UTF-8?B?" + (Base64.getEncoder().encodeToString(fileName.getBytes("UTF-8")))
					        + "?=";
				} else {
					downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
				}
			}
			response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFileName + "\"");
			response.setContentType(fileNode.getFileType()+";charset=UTF-8");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			InputStream input = fileNode.getData().getStream();
			IOUtils.copy(input, output);
			input.close();
			output.close();
		} catch (IOException | RepositoryException e) {
			throw new RuntimeException(e);
		}
	}
}
